<?php

/**
 * @name Base
 * @author Lenovo
 * @desc 默认控制器
 * @see http://www.php.net/manual/en/class.yaf-controller-abstract.php
 */
class Base extends Yaf_Controller_Abstract {
    
    protected $user;
    protected $db;
    protected $likeField = 'title'; 
    protected $deleted_at = true; // 默认 存在 deleted_at 字段 软删除
    protected $isTree = false;
    protected $parentKey = 'pid';
    protected $relations = [];
    protected $order = false;
    public function init() {
        $this->db = Singleton::getDb();
        $token = $this->getRequest()->getServer('HTTP_TOKEN','');
        $key = str_replace('/api/', '', $this->getRequest()->uri);
        $key = str_replace('/', '.', $key); 
        $all = substr($key,0,strpos($key,'.')).'.*';     
        if(!$token){
            error('令牌已失效!',401);
        }else{
            $database = Singleton::getDb();
            $item = $database->get('tokens','*',['token'=>$token]);
            if(!$item){
                error('令牌已失效!',401);
            }
            $user = $database->get('admin_users','*',['id'=>$item['user_id']]);
            if(!$user){
                error('令牌已失效!',401);
            }
            $this->user = $user;
            if($user['role_id'] != 1){
                $ret = $this->db->query("SELECT COUNT(*) FROM admin_permissions where (FIND_IN_SET('".$all."',http_path) OR FIND_IN_SET('".$key."',http_path)) AND id in(SELECT permission_id FROM admin_role_permissions WHERE role_id=".$user['role_id'].")")->fetch();
                if(!$ret[0]){
                    error('无访问权限');
                }
            }
        }
	}

    public function getUser() {
        return $this->user;
    }
}
